/**
 * 安装依赖库
 * npm install crypto-js
 */
import CryptoJS from 'crypto-js';


class Encryption {
    /**
     * 构造函数,传入密钥
     */
    constructor(secretKey) {
        if (typeof secretKey === 'string' && secretKey.length === 16) {
            this.secretKey = secretKey
        } else {
            throw new Error('请输入16位密钥')
        }
    }

    /**
     * 数据加密
     */
    encrypt(data) {
        let content = JSON.stringify({data: data})
        //密钥16位
        var key = CryptoJS.enc.Utf8.parse(this.secretKey);
        var encrypted = CryptoJS.AES.encrypt(content, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString()
    }

    /**
     * 数据解密
     */
    decrypt(str) {
        var ECBOptions = {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        };
        var key = CryptoJS.enc.Utf8.parse(this.secretKey);
        var bytes = CryptoJS.AES.decrypt(str, key, ECBOptions);
        var originalText = bytes.toString(CryptoJS.enc.Utf8);
        if (originalText) {
            let data = JSON.parse(originalText)
            if (typeof data === 'object' && typeof data.data != 'undefined') {
                return data.data
            }
        }
        return null
    }
}

